import React, { useState, useRef, useEffect, useContext} from "react";
import {useHistory} from 'react-router-dom'
import { Modal, Result } from "antd";
import Context from "./context";
import axios from 'axios' ;
import {throttle} from '../../utils/throttle_debounce' ;
import {connect} from 'react-redux';
// import { waitForElementToBeRemoved } from "@testing-library/react";
// 将此拆成子组件就不会数据已修改就影响父组件全局产生数据变化 导致视图变化 355 388
function Scroll({token,flager,UpateUserInfo, getUserInfo}) {
  const [zuobiaoX, setZuobiaoX] = useState(0);
  const [left, setLeft] = useState(0);
  const huakuai = useRef();
  const [flag, setFlag] = useState(false);
  const { state, dispatch } = useContext(Context);
  const [num, setNum] = useState(0);
  const history = useHistory()
  const movehuakuai = (e) => {
    if(flager) {
      return
    }
    setFlag(() => true);
    setNum(() => 1);
    e.persist();
    setZuobiaoX(() => e.clientX - left);
    huakuai.current.style.cursor = "move";
    huakuai.current.style.backgroundPosition = "-6px 30.79625%";
    document.querySelector(".scrollbg").style.opacity = 0;
  };
  const stophuakuai = (e) => {
    if(flager) {
      return
    }
    if (huakuai.current === null ) {
      return 
    }
    setFlag(() => false);
    huakuai.current.style.backgroundPosition = "-6px 12.79625%";
    huakuai.current.style.cursor = "pointer";
    // setTimeout(()=>{
    if (
      Math.floor(Math.abs((state.tux * 386) / 355 - parseInt(huakuai.current.style.left))) <= 3 &&
      parseInt(huakuai.current.style.left) >= 20
    ) {
      setTimeout(() => {
        document.querySelector(".success").style.bottom = 0;
        setTimeout(async() => {
          document.querySelector(".loginModal").style.transform = "scale(0)";
          document.querySelector(".success").style.bottom = "-30px";
          localStorage.setItem('mysystemtoken',token);
          let { data: res } = await axios.get("/ap/user");
          if (res.ok !== 0) {
            getUserInfo({ type: "getuser", data: res.data });
            getUserInfo({ type: "issystemon", flat: "1" });
        //     // getUserInfo({type:'getHistory',history:history})
          }
          const modal = Modal.success({
            icon: null,
            centered: true,
            content: <Result status="success" title="祝贺您登录成功" />,
            mask: false,
            footer: null,
            onCancel:()=> {}
          });
          setTimeout(()=>{
             history.push('/admin')
             modal.destroy();
          },1500)
        }, 800);
      }, 500);
    } else {
      if (huakuai.current.style.cursor === "pointer" && flag == 1) {
        setFlag(() => 0);
        setTimeout(() => {
          document.querySelector(".loginModal").style.animation = "geet 0.2s linear infinite both";
          document.querySelector(".error").style.bottom = 0;
          setTimeout(() => {
            document.querySelector(".loginModal").style.animation = "";
            setTimeout(() => {
              document.querySelector(".front").style.opacity = 0;
              window.document.querySelector(".front").style.left =
              -state.tux + "px";
            }, 300);
            huakuai.current.style.transition = "all 1s";
            huakuai.current.style.left = 0 + "px";

            setTimeout(() => {
              document.querySelector(".error").style.bottom = -30 + "px";
              huakuai.current.style.transition = "";
              setLeft(() => 0);
              dispatch({ type: "chuanzhi", value: 0 });
              document.querySelector(".front").style.opacity = 1;
              document.querySelector(".scrollbg").style.opacity = 1;
            }, 1000);
          }, 400);
        }, 500);
      }
    }
    // },0)
  };
  const moveThuakuai = throttle((e) => {
    if(flager) {
      return
    }
    // huakuai.current.style.left = '' ;
    if (huakuai.current == null ) {
      return 
    }
    // e.persist() ;
    // setFlag(()=>true) // 不需要且不能用flag判斷 只需要让hooks动态改变就行 hooks在dom加载和数据同步 事件执行方面有很多问题
    if (huakuai.current.style.cursor == "move") {
      let leftPosition = e.clientX - zuobiaoX;
      // huakuai.current.style.left = e.clientX - zuobiaoX  +'px'
      if (leftPosition <= 450 - 64 && leftPosition >= 0) {
        if (document.querySelector(".front")) {
          window.document.querySelector(".front").style.left =
            -state.tux + (leftPosition * 355) / 386 + "px";
        }
        setLeft(() => leftPosition);
        dispatch({ type: "chuanzhi", value: leftPosition });
      }
    }
  });

  useEffect(() => {
    // 不能用addEventListener 事件绑定   用dom0级事件 不会因为数据修改 不停地增加dom事件 只会覆盖 原来的 不会重复处罚多次
      window.document.onmousemove = moveThuakuai;
      window.document.onmouseup = stophuakuai;
    //   window.document.addEventListener("mousemove", moveThuakuai, true);
    // window.document.addEventListener("mouseup", stophuakuai, true);
    return () => {
      // window.document
    };
  }, [flag]);
  return (
    <div className="process">
      <span className="scrollbg">按住左边滑块,完成上面的拼图即可登录</span>
      <div
        className="huakuai"
        style={{ left: left + "px" }}
        onMouseDownCapture={movehuakuai}
        //   onClick={()=> {setFlag(()=> false)}}
        ref={huakuai}
      ></div>
    </div>
  );
}

export default connect(
  (state) => state,
  (dispatch) => {
    return {
      getUserInfo: (data) => dispatch(data),
    };
  }
)(Scroll);